#include "online_customer_service_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <time.h>

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "base/logging.h"
#include "base/json_escape.h"
#include "base/config_reader.h"
#include "im/common/common.h"

namespace imserver {
namespace fcgi {

bool OnlineCustomerServiceRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  std::stringstream rsp_stream;

  std::vector<int64_t> qids;
  std::vector<std::string> strs;
  ConfigReader config("../conf/customer_service_list.conf");
  std::string qids_str = config.Get("customer_service_list", "qid_list");
  LOG_DEBUG("qids string : " << qids_str);
  boost::split(
      strs,
      qids_str, 
      boost::is_any_of("|"),
      boost::token_compress_on);

  for (size_t i = 0; i < strs.size(); ++i) {
    int64_t qid = 0;
    try {
      LOG_DEBUG("qid " << i << " = " << strs[i]);
      qid = boost::lexical_cast<int32_t>(strs[i]);
    } catch (boost::bad_lexical_cast & e) {
      continue;
    }
    qids.push_back(qid);
  }

  std::map<int64_t, SessionType::type> online_map;
  if (!qids.empty()) {
    SessionAdapter::Instance().GetOnlineUsers(qids, &online_map);
  }

  rsp_stream << "Content-type: text/javascript; charset=utf-8\r\n\r\n";

  std::vector<int64_t> online_qids;
  std::map<int64_t, SessionType::type>::const_iterator it = online_map.begin();
  for (; it != online_map.end(); ++it) {
    LOG_DEBUG("online qid " << it->first);
    if (SessionType::OFFLINE != it->second) {
      online_qids.push_back(it->first);
    }
  }

  std::string callback = ParseCallback();
  if (!callback.empty()) {
    rsp_stream << ' ' << callback << "(";
  }

  if (!online_qids.empty()) {
    srand((int)time(NULL));
    int index = rand() % online_qids.size();
    rsp_stream << "{\"professional\":" << online_qids[index] << "})";
    LOG_INFO("OnlineCustomerServiceRequest::Response SelectGuide" << online_qids[index]);
  } else {
    if (qids.empty()) {
      rsp_stream << "{\"professional\":" << -1 << "})";
    } else {
      srand((int)time(NULL));
      int index = rand() % qids.size();
      rsp_stream << "{\"professional\":" << qids[index] << "})";
      LOG_INFO("OnlineCustomerServiceRequest::Response SelectGuide" << qids[index]);
    }
  }

  LOG_INFO("OnlineCustomerServiceRequest::Response " << body_ << " rsp=" << rsp_stream.str());
  FCGX_PutS(rsp_stream.str().c_str(), fcgi_out_);
  return true;
}

}
}


